package com.softcits.email.controller;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.softcits.email.auth.SoftCitsUser;
import com.softcits.email.model.LoginUser;
import com.softcits.email.service.UserService;
import com.softcits.email.utils.ResultUtil;

import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * <p>
 * 用户表 前端控制器
 * </p>
 *
 * @author Lan
 * @since 2019-04-04
 */
@RestController
@RequestMapping("/user")
public class UserController {
    
    private final static Logger logger = LoggerFactory.getLogger(UserController.class);

    @Autowired
    private UserService userService;

    @GetMapping("/list")
    public Object list(Integer start, Integer length, HttpServletRequest req) {
        try {
            Thread.sleep(3);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        
       /* Enumeration<String> col = req.getParameterNames();
        while(col.hasMoreElements()) {
            String key = col.nextElement();
            logger.debug("key : " + key + " value : " + req.getParameter(key));
        }*/
        if(null == start || length == null) {
            start = 0;
            length = 10;
        }
        String[][] cm = UserService.columnMapping;
        logger.debug("start = " + start + " order = ");
        String sortDir = req.getParameter("order[0][dir]");
        String columnIndex = req.getParameter("order[0][column]");
        String columnName = req.getParameter(String.format("columns[%s][data]", columnIndex));
        
        /// belows are search criteria
        String search = req.getParameter("search[value]");
        List<String> dbFNList = new ArrayList<String>();
        for(int i = 0; i < cm.length; i++) {
            String searchable = req.getParameter(String.format("columns[%s][searchable]", i));
            if("true".equals(searchable)) {
                dbFNList.add(cm[i][1]);
            }
        }
        
        for(int i = 0; i < cm.length; i++) {
            if(cm[i][0].equals(columnName)) {
                columnName = cm[i][1];
                break;
            }
        }
        
        StringBuilder where = new StringBuilder();
        if(null != search && !"".equals(search)) {
            where.append(" where 1=2 ");
            for(String fn : dbFNList) {
                where.append(" or ");
                where.append(fn).append(" like ").append("'%").append(search).append("%'");
                
            }
        }
        
        String sortcond = "";
        if(columnName != null && sortDir != null) {
            sortcond = String.format("order by %s %s", columnName,sortDir);
        }
        
        return ResultUtil.success(userService.list(start, length, where.toString(), sortcond), userService.getTotals(where.toString()));
    }

    @GetMapping("/hello")
    public ResultUtil hello() {
        return ResultUtil.success("不需要权限也可以访问我啊！");
    }

    @GetMapping("/logout")
    public ResultUtil logout(HttpServletRequest request, HttpServletResponse response) {
        return userService.logout(request, response);
    }
    
    @PostMapping("/register")
    public ResultUtil<String> register(@RequestBody LoginUser userForm, HttpServletRequest request) {
        String code = (String) request.getSession().getAttribute("vcode");
        Long timestamp = (Long) request.getSession().getAttribute("timestamp");
        
        Long currentTime = System.currentTimeMillis();
        
        double timeRange = (currentTime - timestamp) /1000d;
        if(timeRange > 60 ) {
            request.getSession().setAttribute("vcode", "");
            return ResultUtil.error("The validation Code is expired. Please try again later.");
        }
        String vcode = userForm.getVcode();
        if(code.equals(vcode)) {
            int res = this.userService.register(userForm);
            if(res == 2) {
                return ResultUtil.error("Login Name is exsiting, please input another one.");
            } else if(res == 3) {
                return ResultUtil.error("Email is exsiting, please input another one.");
            }
        } else {
            return ResultUtil.error("Validation code is invalide.");
        }
        
        return ResultUtil.success("Register is done");
    }
    
    @PostMapping("/email")
    public ResultUtil<String> emailValidate(String email,HttpServletRequest request) {
        Integer vcode = this.userService.getValidationCode();
        request.getSession().setAttribute("vcode", String.valueOf(vcode));
        request.getSession().setAttribute("timestamp", System.currentTimeMillis());
        
        
        boolean b = this.userService.validateEmail(email, String.valueOf(vcode));
        if(!b) {
            return ResultUtil.error("Email Address is invalid, please check it again.");
        }
        return ResultUtil.success(email);
    }
    
    @PostMapping("/update")
    public Object updateUser(@RequestBody SoftCitsUser userParam) {
        SoftCitsUser user = this.userService.updateUser(userParam);
        
        if(user == null) {
            return ResultUtil.error("Failed to update user : " + userParam.getLoginName());
        }
        
        return ResultUtil.success(user);
    }
    
    @DeleteMapping("/delete/{loginName}")
    public Object deleteUser(@PathVariable("loginName") String loginName) {
        int count = this.userService.deleteUser(loginName);
        
        if(count <= 0) {
           return ResultUtil.error("Failed to delete");
        }
        return ResultUtil.success("Delete Successfully.");
    }
}

